<template>
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    @close="close"
  >
    <!-- 多选框:roleIds选中的角色ID的数组 -->
    <el-checkbox-group v-model="roleIds">
      <!-- 多选的选项   label 存值 -->
      <el-checkbox v-for="role in roleList" :key="role.id" :label="role.id">
        {{ role.name }}
      </el-checkbox>
      <!-- <el-checkbox label="113">开发者</el-checkbox>
      <el-checkbox label="115">人事</el-checkbox> -->
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="assingrole">
        确定
      </el-button>
      <el-button size="small" @click="$emit('update:showRoleDialog')">
        取消
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleList } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
import { assignRoles } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      roleIds: [],
      roleList: [],
      userId: null
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    // 给员工分配角色
    async assingrole () {
      try {
        await assignRoles({ id: this.userId, roleIds: this.roleIds })
        this.$emit('update:showRoleDialog')
        this.$message.success('分配成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 查询用户前分配过的角色 => 回显
    async getUserRoles (id) {
      const { roleIds } = await getUserDetailById(id)
      this.roleIds = roleIds
      // 存储用户ID
      this.userId = id
    },
    close () {
      this.$emit('update:showRoleDialog')
    },
    async getRoleList () {
      const { rows } = await getRoleList({
        page: 1,
        pagesize: 1000
      })
      // console.log('角色列表', rows)
      this.roleList = rows
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-checkbox {
  margin-bottom: 15px;
}
</style>
